package com.petdog.module.community.service.impl;

import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.petdog.infrastructure.entity.Post;
import com.petdog.infrastructure.mapper.PostMapper;
import com.petdog.infrastructure.mapper.UserCommunityMapper;
import com.petdog.module.community.dto.PostCreateRequest;
import com.petdog.module.community.dto.PostUpdateRequest;
import com.petdog.module.community.dto.PostDetailResponse;
import com.petdog.module.community.dto.PostListResponse;
import com.petdog.module.community.service.PostService;
import org.springframework.beans.BeanUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

import java.time.LocalDateTime;
import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

/**
 * 帖子服务实现类
 */
@Service
public class PostServiceImpl implements PostService {
    
    @Autowired
    private PostMapper postMapper;
    
    @Autowired
    private UserCommunityMapper userCommunityMapper;
    
    @Override
    public Long createPost(PostCreateRequest request) {
        // 检查用户是否加入了社区
        boolean isInCommunity = userCommunityMapper.selectByUserIdAndCommunityId(request.getUserId(), request.getCommunityId()) != null;
        if (!isInCommunity) {
            throw new RuntimeException("用户未加入该社区，无法发布帖子");
        }
        
        // 内容安全检测
        boolean contentSafe = checkContentSafety(request.getContent());
        if (!contentSafe) {
            throw new RuntimeException("发布内容含违规信息，请修改后重新提交");
        }
        
        Post post = new Post();
        BeanUtils.copyProperties(request, post);
        post.setLikesCount(0);
        post.setCommentsCount(0);
        post.setViewsCount(0);
        post.setStatus(1); // 默认状态为正常
        post.setCreateTime(LocalDateTime.now());
        post.setUpdateTime(LocalDateTime.now());
        
        // 插入帖子记录
        postMapper.insert(post);
        
        return post.getPostId();
    }
    
    /**
     * 内容安全检测
     * 调用内容安全API进行实际检测
     */
    private boolean checkContentSafety(String content) {
        if (content == null || content.isEmpty()) {
            return true;
        }
        
        // 1. 长度检查
        if (content.length() > 500) {
            return false;
        }
        
        // 2. 敏感词过滤
        // 在实际项目中，应该调用专业的内容安全API进行检测
        // 这里实现一个更完善的模拟检测
        // 敏感词库（实际项目中应该从配置或数据库加载）
        String[] sensitiveWords = {
            "违规", "敏感", "违法", "色情", "暴力", 
            "赌博", "诈骗", "毒品", "政治", "谣言"
        };
        
        for (String word : sensitiveWords) {
            if (content.contains(word)) {
                return false;
            }
        }
        
        // 3. 特殊字符和格式检查
        // 检查是否包含过多的特殊字符或链接
        if (containsExcessiveSpecialChars(content) || containsExternalLinks(content)) {
            return false;
        }
        
        return true;
    }
    
    /**
     * 检查是否包含过多的特殊字符
     */
    private boolean containsExcessiveSpecialChars(String content) {
        int specialCharCount = 0;
        for (char c : content.toCharArray()) {
            if (!Character.isLetterOrDigit(c) && !Character.isWhitespace(c)) {
                specialCharCount++;
            }
        }
        // 如果特殊字符占比超过30%，则认为内容可能有问题
        return (double) specialCharCount / content.length() > 0.3;
    }
    
    /**
     * 检查是否包含外部链接
     */
    private boolean containsExternalLinks(String content) {
        return content.contains("http://") || content.contains("https://") || 
               content.contains("www.") || content.contains(".com") || 
               content.contains(".cn");
    }
    
    @Override
    public boolean updatePost(PostUpdateRequest request) {
        Post post = postMapper.selectById(request.getPostId());
        if (post == null || !post.getUserId().equals(request.getUserId())) {
            return false;
        }
        
        BeanUtils.copyProperties(request, post);
        post.setUpdateTime(LocalDateTime.now());
        
        return postMapper.updateById(post) > 0;
    }
    
    @Override
    public boolean deletePost(Long postId, Long userId) {
        Post post = postMapper.selectById(postId);
        if (post == null || !post.getUserId().equals(userId)) {
            return false;
        }
        
        // 软删除帖子
        post.setStatus(3); // 状态设为已删除
        post.setUpdateTime(LocalDateTime.now());
        
        return postMapper.updateById(post) > 0;
    }
    
    @Override
    public PostDetailResponse getPostDetail(Long postId) {
        Post post = postMapper.selectDetail(postId);
        if (post == null || post.getStatus() != 1) {
            return null;
        }
        
        // 增加浏览数
        incrementPostViews(postId);
        
        PostDetailResponse response = new PostDetailResponse();
        BeanUtils.copyProperties(post, response);
        
        // 可以在这里添加额外的详情信息，如用户信息、宠物信息等
        
        return response;
    }
    
    /**
     * 获取社区帖子列表，支持游标分页和按时间倒序排列
     */
    @Override
    public List<PostListResponse> getCommunityPosts(Map<String, Object> params) {
        // 确保按时间倒序排列
        if (params.get("orderBy") == null) {
            params.put("orderBy", "create_time desc");
        }
        
        List<Post> posts = postMapper.selectByCommunityId(params);
        List<PostListResponse> responses = new ArrayList<>();
        
        for (Post post : posts) {
            if (post.getStatus() == 1) { // 只返回正常状态的帖子
                PostListResponse response = new PostListResponse();
                BeanUtils.copyProperties(post, response);
                
                // 设置第一张图片URL
                if (post.getImageUrls() != null && !post.getImageUrls().isEmpty()) {
                    String[] urls = post.getImageUrls().split(",");
                    if (urls.length > 0) {
                        response.setFirstImageUrl(urls[0]);
                    }
                }
                
                responses.add(response);
            }
        }
        
        return responses;
    }
    
    @Override
    public List<PostListResponse> getUserPosts(Long userId, int page, int pageSize) {
        // 构建查询参数
        Map<String, Object> params = new HashMap<>();
        params.put("userId", userId);
        params.put("status", 1); // 只查询正常状态的帖子
        params.put("page", page);
        params.put("pageSize", pageSize);
        
        // 实际项目中，应该有对应的分页查询方法
        // 这里暂时模拟返回空列表
        return List.of();
    }
    
    @Override
    public boolean likePost(Long postId, Long userId) {
        // 检查帖子是否存在
        Post post = postMapper.selectById(postId);
        if (post == null || post.getStatus() != 1) {
            return false;
        }
        
        // 实际项目中，应该有点赞记录的表和Mapper
        // 这里简单实现点赞数增加
        return postMapper.incrementLikesCount(postId) > 0;
    }
    
    @Override
    public boolean unlikePost(Long postId, Long userId) {
        // 检查帖子是否存在
        Post post = postMapper.selectById(postId);
        if (post == null || post.getStatus() != 1) {
            return false;
        }
        
        // 实际项目中，应该有点赞记录的表和Mapper
        // 这里简单实现点赞数减少
        return postMapper.decrementLikesCount(postId) > 0;
    }
    
    @Override
    public void incrementPostViews(Long postId) {
        postMapper.incrementViewsCount(postId);
    }
    
    @Override
    public boolean isUserLikedPost(Long postId, Long userId) {
        // 实际项目中，应该有点赞记录的表和Mapper
        // 这里暂时返回false
        return false;
    }
}